﻿using System;
using System.Collections.Generic;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class PlayerHealthManager : SingletonMono<PlayerHealthManager>
{
    public List<Sprite> player2HeadSprites;
    
    public GameObject player1Head;
    public GameObject player2Head;
    
    public TextMeshPro player1HealthText;
    public TextMeshPro player2HealthText;

    public IntVariable player1HealthValue;
    public IntVariable player2HealthValue;

    public int Player1HealthValue
    {
        get => player1HealthValue.currentValue;
        set => player1HealthValue.SetValue(value);
    }


    public int Player2HealthValue
    {
        get => player2HealthValue.currentValue;
        set => player2HealthValue.SetValue(value);
    }


    private void OnEnable()
    {
        EventCenter.GetInstance().AddEventListener<ChessSide,int>(nameof(DeductCharacterHp),DeductCharacterHp);
        EventCenter.GetInstance().AddEventListener<int>("Player1HpValueChange", Player1HealthValueChange);
        EventCenter.GetInstance().AddEventListener<int>("Player2HpValueChange", Player2HealthValueChange);
        
    }

    


    private void OnDisable()
    {
        EventCenter.GetInstance().RemoveEventListener<ChessSide,int>(nameof(DeductCharacterHp),DeductCharacterHp);
    }

    public void GameStart()
    {
        player1Head.SetActive(true);
        player2Head.SetActive(true);
        player1HealthText.gameObject.SetActive(true);
        player2HealthText.gameObject.SetActive(true);

        Player1HealthValue = 30;
        Player2HealthValue = 30;

    }

    private void DeductCharacterHp(ChessSide side,int amount)
    {
        if(side == ChessSide.Player1)
        {
            if (Player2HealthValue <= amount)
            {
                
                 EventCenter.GetInstance().EventTrigger("Win");

            }
            else if (Player2HealthValue > amount)
            {
                Player2HealthValue -= amount;
            }
        }else if(side == ChessSide.Player2)
        {
            if (Player1HealthValue <= amount)
            {

                EventCenter.GetInstance().EventTrigger("Defeat");

            }
            else if (Player1HealthValue > amount)
            {
                Player1HealthValue -= amount;
            }
        }
    }
    
   
    public void GameOver()
    {
        player1Head.SetActive(false);
        player2Head.SetActive(false);

        player1HealthText.gameObject.SetActive(false);
        player2HealthText.gameObject.SetActive(false);
    }


    private void Player2HealthValueChange(int arg0)
    {
        player2HealthText.text = arg0.ToString();
    }

    private void Player1HealthValueChange(int arg0)
    {
        player1HealthText.text = arg0.ToString();
    }
}
